package helper;

import image.Analyzer;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.ListIterator;

import android.os.Environment;

public class FileIOHelper {

	private static String path;

	public static void newFolder(String newFolder) {
		String extStorageDirectory = Environment.getExternalStorageDirectory()
				.toString();
		File myNewFolder = new File(extStorageDirectory + newFolder);
		myNewFolder.mkdir();
		path = "mnt/sdcard/" + newFolder + "/";
	}

	public static void writeToFile(String name, Analyzer analyzer, int w, int h)
			throws IOException {
		File file = new File(path + name + ".txt");

		FileWriter fw = new FileWriter(file);
		BufferedWriter out = new BufferedWriter(fw);
		LinkedList<double[]> data;
		data = analyzer.getData();
		out.write(w + " " + h + "\n");
		for (ListIterator<double[]> it = data.listIterator(); it.hasNext();) {
			double v[] = it.next();
			for (int j = 0; j < 5; j++) {
				out.write(v[j] + " ");
			}
			out.write("\n");
		}

		out.close();
	}

	public static String getFullPath(String name) {
		return path + name + ".txt";
	}

	public static LinkedList<double[]> resultFromFile(String fileName)
			throws NumberFormatException, IOException {
		File txt = new File(fileName);
		FileReader fr = new FileReader(txt);
		BufferedReader in = new BufferedReader(fr);

		LinkedList<double[]> result = new LinkedList<double[]>();
		String line;
		String[] temp = in.readLine().split(" ");
		double[] TEMP = new double[2];
		TEMP[0] = Double.parseDouble(temp[0]);
		TEMP[1] = Double.parseDouble(temp[1]);
		result.offer(TEMP);
		while ((line = in.readLine()) != null) {
			String[] sor = line.split(" ");
			double[] nrline = new double[5];
			for (int j = 0; j < 5; j++) {
				nrline[j] = Double.parseDouble(sor[j]);
			}
			result.offer(nrline);
		}

		in.close();
		return result;
	}
}
